package com.utils;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author zxl
 * @create :2022/9/28
 */
//专门用来打开数据库连接的工具类
public class JDBCUtils {
    //最终需要通过数据源获得一个连接 定义全局变量
   private static DruidDataSource dataSource = null;

    //静态代码块   类一加载的时候就会运行
    static {
        try {
            Properties properties = new Properties();
            properties.load(
             JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")

            );
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取连接的方法
     * @return  返回获取到的连接
     */
    public static Connection getConn(){
        Connection conn=null;
        try {
             conn = dataSource.getConnection();
            System.out.println(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**关闭连接的方法
     *
     */
    public  static void closeConn(Connection conn, PreparedStatement pst, ResultSet rs){
        try {
            if (rs != null) {
                rs.close();
            }

            if (pst != null) {
                pst.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    //关闭的方法2
    public static void closeConn2(Connection conn){
        DbUtils.closeQuietly(conn);
    }


}
